import { ref , readonly} from 'vue';
import { editMenoItemApi, getMenoDataAllApi, getMenoItemLikeApi, getMenoDataByIdApi, deleteMenoDataItemByIdApi , getMenoDataTop4Api } from '../apis/meonApi';
import { cloneDeep , debounce } from 'lodash';
import useOrderByData from './useOrderByData';

export default function useMeonDataFun() {

    const menoListRef = ref([]);
    const menoListTop4Ref = ref([]);
    const searchMenoListRef = ref([])
    const searchMenoLodingRef = ref(false);

    const menoListReadonly=readonly(menoListRef)
    const menoListTop4Readonly=readonly(menoListTop4Ref)
    const searchMenoListReadonly = readonly(searchMenoListRef)
    const searchMenoLodingReadonly = readonly(searchMenoLodingRef);


    // 新增
    const editMenoItemFun = async (param) => {
        return await editMenoItemApi(param);
    }

    // 获取全部数据
    const getMenoDataList = async () => {
        const { code, rows } = await getMenoDataAllApi();
        if (code === 200) {
            const orderByList = await useOrderByData(rows);
            menoListRef.value = orderByList;
        }
    }

    // 获取top4数据
    const getMenoDataListTop4 = async () => {
        const { code, rows } = await getMenoDataTop4Api();
        if (code === 200) {
            const orderByList = await useOrderByData(rows);
            menoListTop4Ref.value = orderByList;
        }
    }

    // 根据id获取数据
    const getMenoDataItem =async (id) => {
        const { code, data } = await getMenoDataByIdApi(id);
        if (code === 200) {
            return data
        }
    }

    // id删除
    const deleteMenoDataItem = async (id) => {
        await deleteMenoDataItemByIdApi(id);
        getMenoDataList();
    }

    // 搜索
    const searchMenoList = async (value) => {
        searchMenoLodingRef.value = true;
        await searchFun(value);
    }
    const searchFun = debounce(async (value) => {
        try {
            if (value) {
                const { code, rows } = await getMenoItemLikeApi({ name: value })
                if (code === 200) {
                    searchMenoListRef.value = rows;
                }
            } else {
                await getMenoDataList()
                searchMenoListRef.value = cloneDeep(menoListRef.value);
            }
        } finally {
            searchMenoLodingRef.value = false;
        }
    },300)

    return {
        menoListReadonly,
        menoListTop4Readonly,
        searchMenoListReadonly,
        searchMenoLodingReadonly,
        editMenoItemFun,
        getMenoDataList,
        getMenoDataItem,
        deleteMenoDataItem,
        searchMenoList,
        getMenoDataListTop4,
    }
}